<?php
$template_path = get_template_directory();
include $template_path.'/inc/init.php';
include $template_path.'/inc/wp-panels.php';
include $template_path.'/inc/wp-postviews.php';
include $template_path.'/inc/admin-options.php';
include $template_path.'/inc/wp-collect.php';

global $table_prefix, $wpdb;
$table_name = $wpdb->prefix."collect";
$sql1 = "CREATE TABLE IF NOT EXISTS ".$table_name." (
  `c_id` int(11) NOT NULL AUTO_INCREMENT,
   c_userid int(11) NOT NULL,
  `c_posttitle` text NOT NULL,
  `c_posturl` text NOT NULL,
  `c_postid` text NOT NULL,
  `c_ip` varchar(40) NOT NULL,
  `c_time` datetime NOT NULL,
  PRIMARY KEY (`c_id`),
  KEY `c_time` (`c_time`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4;";

$sql2 = "CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}diggc_log` (
               `vlid` bigint(20) unsigned NOT NULL auto_increment,
               `userid` bigint(20) unsigned NOT NULL,
			   `cid` bigint(20) unsigned NOT NULL,
               `ip` char(15) default NULL,
               `time` datetime NOT NULL,
                PRIMARY KEY (`vlid`)
            );";
$sql3 = "CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}undiggc_log` (
               `vlid` bigint(20) unsigned NOT NULL auto_increment,
               `userid` bigint(20) unsigned NOT NULL,
			   `cid` bigint(20) unsigned NOT NULL,
               `ip` char(15) default NULL,
               `time` datetime NOT NULL,
                PRIMARY KEY (`vlid`)
            );";
$sql4 = "CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}reports` (
               `rid` bigint(20) unsigned NOT NULL auto_increment,
               `rname` varchar(50) NOT NULL,
			   `postid` bigint(20) NOT NULL,
               `posturl` varchar(100) default NULL,
			   `rcontent` text default NULL,
               `time` datetime NOT NULL,
                PRIMARY KEY (`rid`)
            );";
$sql5 = "CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}integration` (
               `in_id` bigint(20) unsigned NOT NULL auto_increment,
               `userid` bigint(20) NOT NULL,
			   `username` varchar(50) NOT NULL,
			   `postid` bigint(20) NOT NULL,
               `time` datetime NOT NULL,
                PRIMARY KEY (`in_id`)
            );";									
$sql6 = "CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}sp_posts` (
               `sp_id` bigint(20) unsigned NOT NULL auto_increment,
               `post_id` bigint(20) NOT NULL,
			   `specialt_id` bigint(50) NOT NULL,
               `time` datetime NOT NULL,
                PRIMARY KEY (`sp_id`)
            );";									

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

dbDelta($sql1); dbDelta($sql2); dbDelta($sql3); dbDelta($sql4); dbDelta($sql5); dbDelta($sql6); 	

register_nav_menus( array(
	'primary' => __( '菜单一', 'iglei' ),
	'second' => __( '菜单二', 'iglei' ),
) );


/*用户登陆*/
	add_action( 'wp_ajax_nopriv_user-login',  'user_login_httpr' );
	//do_action( 'wp_ajax_user-login' );
	function user_login_httpr(){
		//print_r($_POST);
		$return = array(); //What we send back
		if(!$_REQUEST['redirect_to']){
		if( !empty($_REQUEST['log']) && !empty($_REQUEST['pwd']) && trim($_REQUEST['log']) != '' && trim($_REQUEST['pwd'] != '') ){
			$loginResult = wp_signon();
			$user_role = 'null';
			
			if ( strtolower(get_class($loginResult)) == 'wp_user' ) {
				$current_user = $loginResult;
				$redirect = getLoginRedirect($current_user); 
				$return['success'] = 1;
				session_start();
				$_SESSION['log'] =$_REQUEST['log'];
				$_SESSION['pwd'] =$_REQUEST['pwd'];
				SetCookie("auth_key", '111', time()+3600);
			}elseif ( strtolower(get_class($loginResult)) == 'wp_error' ) {
					$return['success'] = 0;
			}
				echo json_encode( $return );exit;
				//is_user_logged_in();
		}
		}
	}
//用户注册/
	add_action( 'wp_ajax_nopriv_user-register',  'user_register_httpr' );
	function user_register_httpr(){
		$return = array(); //What we send back
		if( !empty($_REQUEST['log']) && !empty($_REQUEST['email']) && !empty($_REQUEST['pwd']) && trim($_REQUEST['log']) != '' && trim($_REQUEST['pwd'] != '') && trim($_REQUEST['email'] != '')){
		 if(username_exists($_POST['log'])){
			 $return['success'] = '用户名已经被注册!';
		 }elseif(email_exists($_POST['email'])){	
		 	$return['success'] = '邮箱已经被注册!';
		 }else{
			include (ABSPATH.'member/re_config.php');
			$uid = uc_user_register($_POST['log'], $_POST['pwd'], $_POST['email']);
			if($uid <= 0) {
				if($uid == -1) {
					$return['success'] = '用户名不合法';
				} elseif($uid == -2) {
					$return['success'] = '包含要允许注册的词语';
				} elseif($uid == -3) {
					$return['success'] = '用户名已经存在';
				} elseif($uid == -4) {
					$return['success'] = 'Email 格式有误';
				} elseif($uid == -5) {
					$return['success'] = 'Email 不允许注册';
				} elseif($uid == -6) {
					$return['success'] = '该 Email 已经被注册';
				} else {
					$return['success'] = '未定义';
				}
			} else {
				$uid = wp_create_user( $_POST['log'], $_POST['pwd'], $_POST['email'] );
				if($uid){
					$return['success'] = 1;
				}else{
					$return['success'] = '注册失败！';
				}
			}
		 }
			echo json_encode( $return );exit;
				//is_user_logged_in();
		}
	}	
//专题前台js 数据中心
if ( is_user_logged_in() ){
	add_action( 'wp_ajax_add_video',  'add_video_httpr' );
	add_action( 'wp_ajax_tag',  'tag_httpr' );
	add_action( 'wp_ajax_ad',   'ad_httpr'  );
}else{
	add_action( 'wp_ajax_nopriv_add_video',  'add_video_httpr' );
	add_action( 'wp_ajax_nopriv_tag',  'tag_httpr' );
	add_action( 'wp_ajax_nopriv_ad',   'ad_httpr');
}	
	function add_video_httpr(){
		global $table_prefix, $wpdb;
		//print_r($_POST);
		if(!is_numeric($_POST['post_id'])){
			echo "-1";
			exit;
		}
		$data = $wpdb->get_results("SELECT * FROM ".$table_prefix."posts where ID = '".$_POST['post_id']."' and ".$table_prefix."posts.post_status = 'publish' and (".$table_prefix."posts.post_type = 'cgvideo' OR ".$table_prefix."posts.post_type = 'animation' OR ".$table_prefix."posts.post_type = 'musics' OR ".$table_prefix."posts.post_type = 'recreation' OR ".$table_prefix."posts.post_type = 'advisory')");
		if($data){
			$request = $wpdb->get_results("SELECT * FROM ".$table_prefix."sp_posts where post_id = '".$_POST['post_id']."'");
			if($request){echo "-2";exit;}else{
				$ret = $wpdb->get_results("INSERT INTO ".$table_prefix."sp_posts (post_id,specialt_id,time) VALUES (".$_POST['post_id'].",".$_POST['specialt_id'].",now())");
				
				echo "0";
			}
		}else{
			echo "-1";
			exit;	
		}
		exit;
	}
	
	function tag_httpr(){
		$sp_alias = get_post_meta($_POST['specialt_id'], 'sp_alias', true);
		if(!$sp_alias){
			echo '<div class="no_more">没有更多信息</div>';
		}else{
			$alias = explode(",",$sp_alias);
		}
		$argscount = array(
			'numberposts' => -1,
			'meta_key' =>'views',
			'order' => 'DESC',
			'orderby' => 'meta_value_num',
			'post_type' => array('cgvideo','animation'),
			'tax_query' => array(
				array(
					'taxonomy' => 'post_tag',
					'field' => 'slug',
					'terms' => $alias
				)
			)
		);
		if($_POST['order'] == 'hot'){
			$args = array(
				'numberposts' => 15,
				'paged' => $_POST['page'] ,
				'meta_key' =>'views',
				'order' => 'DESC',
				'orderby' => 'meta_value_num',
				'post_type' => array('cgvideo','animation'),
				'tax_query' => array(
					array(
						'taxonomy' => 'post_tag',
						'field' => 'slug',
						'terms' => $alias
					)
				)
			);
		}else{
			$args = array(
				'numberposts' => 15,
				'paged' => $_POST['page'] ,
				'order' => 'DESC',
				'orderby' => 'post_date',
				'post_type' => array('cgvideo','animation'),
				'tax_query' => array(
					array(
						'taxonomy' => 'post_tag',
						'field' => 'slug',
						'terms' => $alias
					)
				)
			);
		}
		$postslist = get_posts( $args );

		$count = count(get_posts( $argscount ));
		$mun = ceil($count / 15);
		if($postslist){
			foreach($postslist as $post){
				$img = get_post_meta($post->ID , 'show_image', true);
				$html .= '<div id="jq_po_0" yb="4" pf="985" "="" txt="" tg="2011-12-02 07:21" lm="" dm="1774" subtitle="" pl="36" sc="350" gk="23630" class="po"> <a target="_blank" href="'.get_permalink($post->ID).'"><img src="'.$img.'" _src="">
  <div class="vbg"></div>
  <div class="t">'.$post->post_title.'</div>
  </a>
  <div class="z"><i>4 (+985)</i><b>4:15</b></div>
  <div class="i"><b class="c1">23630</b><b class="c2">1774</b></div>
</div>';
			}
			
			if($_POST['page']<11){
				for($i=1;$i <= $mun;$i++){
					if($i == $_POST['page']){
						$page .='<strong>'.$i.'</strong>';
					}else{
						$page .='<a href="javascript:loadSpPage(\'tag\',\'hot\','.$i.');">'.$i.'</a>';	
					}
				}
			}else{
				if(($_POST['page']+5)<=$mun){
					$c = $_POST['page']+5;
				}else{
					$c = $mun;
				}
				
				for($i=($_POST['page']-5);$i <= $c;$i++){
					if($i == $_POST['page']){
						$page .='<strong>'.$i.'</strong>';
					}else{
						$page .='<a href="javascript:loadSpPage(\'tag\',\'hot\','.$i.');">'.$i.'</a>';	
					}	
				}
			}
			if($_POST['page']!=$mun){
				$next = '<a href="javascript:loadSpPage(\'tag\',\'hot\','.($_POST['page']+1).');" class="nextPage">下页</a>';
			}
			$html .= '<div class="pagelistbox">
						<span>共 '.$mun.' 页/'.$count.' 个视频 </span>
						<a href="javascript:loadSpPage(\'tag\',\'hot\',1);" class="indexPage">首页 </a> 
						'.$page.$next.'
						<a href="javascript:loadSpPage(\'tag\',\'hot\','.$mun.');" class="endPage">末页</a>
						<input type="text" u="javascript:loadSpPage(\'tag\',\'hot\',[PAGE]);" class="custompage">
						<a onclick="window.location=$(this).parent().find(\'.custompage\').attr(\'u\').replace(\'[PAGE]\',$(this).parent().find(\'.custompage\').val())" class="button">确定</a>
					</div>';
			echo $html;
			
		}else{
			echo '<div class="no_more">没有更多信息</div>';
		}
		//print_r($postslist);
		exit;
	}
	
	function ad_httpr(){
		global $table_prefix, $wpdb;
		$page = $_POST['page']-1;
		$start = $page * 15;
		$Lastpage = $page * 15 +15;
		
		if($_POST['order'] == 'new'){
			$data = $wpdb->get_results("select * from ".$table_prefix."posts left join ".$table_prefix."sp_posts on ".$table_prefix."posts.ID = ".$table_prefix."sp_posts.post_id where ".$table_prefix."sp_posts.specialt_id = '".$_POST['specialt_id']."' ORDER BY ".$table_prefix."posts.post_date DESC LIMIT ".$start.", ".$Lastpage."");
		}else{
			$data = $wpdb->get_results("select * from ".$table_prefix."posts left join (".$table_prefix."sp_posts ,".$table_prefix."postmeta)on (".$table_prefix."posts.ID = ".$table_prefix."sp_posts.post_id and ".$table_prefix."sp_posts.post_id = ".$table_prefix."postmeta.post_id)where (".$table_prefix."sp_posts.specialt_id = '".$_POST['specialt_id']."' and ".$table_prefix."postmeta.meta_key = 'views' ) ORDER BY ".$table_prefix."postmeta.meta_value DESC LIMIT ".$start.", ".$Lastpage);
		}
			
		//$count = $wpdb->fetch_row($db->query("SELECT FOUND_ROWS();"));
		$count = $wpdb->num_rows;
		$mun = ceil($count / 15);
		if($data){
			foreach($data as $post){
				$img = get_post_meta($post->ID , 'show_image', true);
				$html .= '<div id="jq_po_0" yb="4" pf="985" "="" txt="" tg="2011-12-02 07:21" lm="" dm="1774" subtitle="" pl="36" sc="350" gk="23630" class="po"> <a target="_blank" href="'.get_permalink($post->ID).'"><img src="'.$img.'" _src="">
  <div class="vbg"></div>
  <div class="t">'.$post->post_title.'</div>
  </a>
  <div class="z"><i>4 (+985)</i><b>4:15</b></div>
  <div class="i"><b class="c1">23630</b><b class="c2">1774</b></div>
</div>';
			}
			
			if($_POST['page']<11){
				for($i=1;$i <= $mun;$i++){
					if($i == $_POST['page']){
						$page .='<strong>'.$i.'</strong>';
					}else{
						$page .='<a href="javascript:loadSpPage(\'tag\',\'hot\','.$i.');">'.$i.'</a>';	
					}
				}
			}else{
				if(($_POST['page']+5)<=$mun){
					$c = $_POST['page']+5;
				}else{
					$c = $mun;
				}
				
				for($i=($_POST['page']-5);$i <= $c;$i++){
					if($i == $_POST['page']){
						$page .='<strong>'.$i.'</strong>';
					}else{
						$page .='<a href="javascript:loadSpPage(\'tag\',\'hot\','.$i.');">'.$i.'</a>';	
					}	
				}
			}
			if($_POST['page']!=$mun){
				$next = '<a href="javascript:loadSpPage(\'tag\',\'hot\','.($_POST['page']+1).');" class="nextPage">下页</a>';
			}
			$html .= '<div class="pagelistbox">
						<span>共 '.$mun.' 页/'.$count.' 个视频 </span>
						<a href="javascript:loadSpPage(\'tag\',\'hot\',1);" class="indexPage">首页 </a> 
						'.$page.$next.'
						<a href="javascript:loadSpPage(\'tag\',\'hot\','.$mun.');" class="endPage">末页</a>
						<input type="text" u="javascript:loadSpPage(\'tag\',\'hot\',[PAGE]);" class="custompage">
						<a onclick="window.location=$(this).parent().find(\'.custompage\').attr(\'u\').replace(\'[PAGE]\',$(this).parent().find(\'.custompage\').val())" class="button">确定</a>
					</div>';
			echo $html;
			
		}else{
			echo '<div class="no_more">没有更多信息</div>';
		}
		exit;
	}
	
//用户注册/
	function getLoginRedirect($user){
		if($data['login_redirect'] != ''){
			$redirect = $data["login_redirect"];
		}
		if( strtolower(get_class($user)) == "wp_user" ){
			$user_role = array_shift($user->roles); //Checking for role-based redirects
			if( isset($data["role_login"][$user_role]) ){
				$redirect = $data["role_login"][$user_role];
			}
		}
		//Do string replacements
		$redirect = str_replace('%USERNAME%', $user->user_login, $redirect);
		$redirect = str_replace("%LASTURL%", $_SERVER['HTTP_REFERER'], $redirect);
		return $redirect;
	}


add_theme_support( 'post-thumbnails' );

function twentyten_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	global $commentcount;
	$current_user = wp_get_current_user();
	if(!$commentcount) {
	  $page = get_query_var('cpage')-1;
	  $cpp=get_option('comments_per_page');
	  $commentcount = $cpp * $page;
	 }
	switch ( $comment->comment_type ) :
		case '' :
	?>
	<li <?php comment_class(); ?> id="l_id_<?php comment_ID(); ?>">
    <?php  
		$commentid = $comment->comment_ID;
		$digg_count = get_comment_meta($commentid, '_digg', true);
		if(empty($digg_count)){ $digg_count = 0; }else{ $digg_count = $digg_count; }
		$undigg_count = get_comment_meta($commentid, '_undigg', true);
		if(empty($undigg_count)){ $undigg_count = 0; }else{ $undigg_count = $undigg_count; }
	?>
		<div id="comment-<?php comment_ID(); ?>">
		<div class="comment-author vcard">
        <?php echo get_avatar( $comment, 40 ); ?>
<div class="t">        
<div style="float:left; color:#AAAAAA; margin-right:5px;">
<?php if(!$parent_id = $comment->comment_parent) {printf('#%1$s', ++$commentcount);} ?>
</div>		
			<?php printf( __( '%s', 'iglei' ), sprintf('<cite class="fn">%s</cite>', get_comment_author_link())); ?>
</div>            
		</div><!-- .comment-author .vcard -->
		<?php if ( $comment->comment_approved == '0' ) : ?>
			<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentyten' ); ?></em>
			<br />
		<?php endif; ?>

		<div class="comment-body"><?php comment_text(); ?></div>
 
		<div class="comment-meta commentmetadata" style="float:left;">
         <?php echo human_time_diff(get_comment_time('U'),current_time('timestamp')).'前'; ?> 
		</div><!-- .comment-meta .commentmetadata -->
        <div class="rev"><a class="agree" href="#" onclick="return agFB(this,'<?php echo $current_user->ID;  ?>','<?php echo $digg_count;  ?>','<?php comment_ID(); ?>')">赞同<span id="digg">(+<?php echo $digg_count;  ?>)</span></a><a class="unagree" href="#" onclick="return dagFB(this,'<?php echo $current_user->ID;  ?>','<?php echo $undigg_count;  ?>','<?php comment_ID(); ?>')" >反对<span id="undigg">(+<?php echo $undigg_count;  ?>)</span></a><a class="rep" href="javascript:replyFB(<?php comment_ID(); ?>);set_qure(<?php comment_ID(); ?>);" >回复</a></div>
        <div style="clear:both;"></div>
		<div class="reply">
			<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
		</div><!-- .reply -->
	</div><!-- #comment-##  -->

	<?php
			break;
		case 'pingback'  :
		case 'trackback' :
	?>
    
	<li class="post pingback">
		<p><?php _e( 'Pingback:', 'twentyten' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( '(Edit)', 'twentyten' ), ' ' ); ?></p>
	<?php
			break;
	endswitch;
}

function comment_forms( $args = array(), $post_id = null ) {
	global $id;

	if ( null === $post_id )
		$post_id = $id;
	else
		$id = $post_id;

	$commenter = wp_get_current_commenter();
	$user = wp_get_current_user();
	$user_identity = $user->exists() ? $user->display_name : '';

	$req = get_option( 'require_name_email' );
	$aria_req = ( $req ? " aria-required='true'" : '' );
	$fields =  array(
		'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
		            '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',
		'email'  => '<p class="comment-form-email"><label for="email">' . __( 'Email' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
		            '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',
		'url'    => '<p class="comment-form-url"><label for="url">' . __( 'Website' ) . '</label>' .
		            '<input id="url" name="url" type="text" value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
	);

	$required_text = sprintf( ' ' . __('Required fields are marked %s'), '<span class="required">*</span>' );
	$defaults = array(
		'fields'               => apply_filters( 'comment_form_default_fields', $fields ),
		'comment_field'        => '<p class="comment-form-comment"><label for="comment">请自觉遵守互联网相关的政策法规，严禁发布色情、暴力、反动的言论。</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>',
		'must_log_in'          => '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
		'logged_in_as'         => '',
		'comment_notes_before' => '<p class="comment-notes">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>',
		'comment_notes_after'  => '',
		'id_form'              => 'commentform',
		'id_submit'            => 'submit',
		'title_reply'          => '',
		'title_reply_to'       => '',
		'cancel_reply_link'    => '',
		'label_submit'         => __( 'Post Comment' ),
	);

	$args = wp_parse_args( $args, apply_filters( 'comment_form_defaults', $defaults ) );

	?>
		<?php if ( comments_open( $post_id ) ) : ?>
			<?php do_action( 'comment_form_before' ); ?>
			<div id="respond">
				<h3 id="reply-title"><?php comment_form_title( $args['title_reply'], $args['title_reply_to'] ); ?> <small><?php cancel_comment_reply_link( $args['cancel_reply_link'] ); ?></small></h3>
				<?php if ( get_option( 'comment_registration' ) && !is_user_logged_in() ) : ?>
					<?php echo $args['must_log_in']; ?>
					<?php do_action( 'comment_form_must_log_in_after' ); ?>
				<?php else : ?>
					<form action="<?php echo site_url( '/wp-comments-post.php' ); ?>" method="post" id="<?php echo esc_attr( $args['id_form'] ); ?>">
						<?php do_action( 'comment_form_top' ); ?>
						<?php if ( is_user_logged_in() ) : ?>
							<?php echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity ); ?>
							<?php do_action( 'comment_form_logged_in_after', $commenter, $user_identity ); ?>
						<?php else : ?>
							<?php echo $args['comment_notes_before']; ?>
							<?php
							do_action( 'comment_form_before_fields' );
							foreach ( (array) $args['fields'] as $name => $field ) {
								echo apply_filters( "comment_form_field_{$name}", $field ) . "\n";
							}
							do_action( 'comment_form_after_fields' );
							?>
						<?php endif; ?>
						<?php echo apply_filters( 'comment_form_field_comment', $args['comment_field'] ); ?>
						<?php echo $args['comment_notes_after']; ?>
						<div class="_qure"><div class="t"></div></div>
                        <p class="form-submit">
							<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
							<?php comment_id_fields( $post_id ); ?>
						</p>
						<?php do_action( 'comment_form', $post_id ); ?>
					</form>
				<?php endif; ?>
			</div><!-- #respond -->
			<?php do_action( 'comment_form_after' ); ?>
		<?php else : ?>
			<?php do_action( 'comment_form_comments_closed' ); ?>
		<?php endif; ?>
	<?php
}
/*选择下了分类*/
function select($cat ,$catid){
	$args = array(
			'show_option_none'   => '',
			'show_count'         => 1,
			'hide_empty'         => 0, 
			'echo'               => 0,
			'selected'           => $catid,
			'hierarchical'       => 1, 
			'name'               => $cat,
			'id'                 => '',
			'class'              => 'postform',
			'depth'              => 0,
			'tab_index'          => 0,
			'taxonomy'           => $cat,
			'hide_if_empty'      => 1
		);
		$select = wp_dropdown_categories($args);
		$select = preg_replace("#<select([^>]*)>#", "", $select);
		$select = preg_replace("#</select([^>]*)>#", "", $select);
	return $select;
  }
  
 //上传图片类
 

class upphoto{
	public $previewsize=0.125  ;   //预览图片比例
	public $preview=1;   //是否生成预览，是为1，否为0
	public $datetime;   //随机数
	public $ph_name;   //上传图片文件名
	public $image_url; //图片URL
	public $ph_tmp_name;    //图片临时文件名
	public $ph_path="../wp-content/uploads/images/";    //上传文件存放路径
	public $ph_type;   //图片类型
	public $ph_size;   //图片大小
	public $imgsize;   //上传图片尺寸，用于判断显示比例
	public $al_ph_type=array('image/jpg','image/jpeg','image/png','image/pjpeg','image/gif','image/bmp','image/x-png');    //允许上传图片类型
	public $al_ph_size=1000000;   //允许上传文件大小
  function __construct(){
    $this->set_datatime();
  }
  function set_datatime(){
   $this->datetime=date("YmdHis");
  }
   //获取文件类型
  function get_ph_type($phtype){
     $this->ph_type=$phtype;
  }
  //获取文件大小
  function get_ph_size($phsize){
     $this->ph_size=$phsize."<br>";
  }
  //获取上传临时文件名
  function get_ph_tmpname($tmp_name){
    $this->ph_tmp_name=$tmp_name;
    $this->imgsize=getimagesize($tmp_name);
  }
  //获取原文件名
  function get_ph_name($phname){
    $this->ph_name=$this->ph_path.$this->datetime.strrchr($phname,"."); //strrchr获取文件的点最后一次出现的位置
	$this->image_url = home_url()."/wp-content/uploads/images/".$this->datetime.strrchr($phname,"."); //图片绝对地址
 //$this->ph_name=$this->datetime.strrchr($phname,"."); //strrchr获取文件的点最后一次出现的位置
 return $this->ph_name;
  }
 //判断上传文件存放目录
  function check_path(){
    if(!file_exists($this->ph_path)){
     mkdir($this->ph_path);
    }
  }
  //判断上传文件是否超过允许大小
  function check_size(){
    if($this->ph_size>$this->al_ph_size){
     $this->showerror("上传图片超过2000KB");
    }
  }
  //判断文件类型
  function check_type(){
   if(!in_array($this->ph_type,$this->al_ph_type)){
         $this->showerror("上传图片类型错误");
   }
  }
  //上传图片
   function up_photo(){
   if(!move_uploaded_file($this->ph_tmp_name,$this->ph_name)){
    $this->showerror("上传文件出错");
   }
  }
  //图片预览
   function showphoto(){
      if($this->preview==1){
      if($this->imgsize[0]>2000){
        $this->imgsize[0]=$this->imgsize[0]*$this->previewsize;
             $this->imgsize[1]=$this->imgsize[1]*$this->previewsize;
      }
         echo('<img src="'.$this->ph_name.'" width="'.$this->imgsize["0"].'" height="'.$this->imgsize["1"].'">');
     }
   }
  //错误提示
  function showerror($errorstr){
    echo "<mce:script language=javascript><!--
alert('$errorstr');location='javascript:history.go(-1);';
// --></mce:script>";
   exit();
  }
  function save(){
   $this->check_path();
   $this->check_size();
   $this->check_type();
   $this->up_photo();
   $this->showphoto();
   return $this->image_url;
  }
}

//获取收藏列表
function favorite($temple=1){
	global $table_prefix, $wpdb;
	if($temple==3){
			$data = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS  * FROM ".$table_prefix."posts  INNER JOIN ".$table_prefix."postmeta ON (".$table_prefix."posts.ID = ".$table_prefix."postmeta.post_id) WHERE 1=1  AND ".$table_prefix."posts.post_status = 'publish' AND (".$table_prefix."posts.post_type != 'specialt') AND (".$table_prefix."postmeta.meta_key = '_postcollect' ) GROUP BY ".$table_prefix."posts.ID ORDER BY ".$table_prefix."postmeta.meta_value+0 DESC LIMIT 0, 10");
			
			foreach ($data as $k){
				$postimg = get_post_meta($k->ID,'show_image',true);
				if(empty($postimg)){
					$postimg = get_bloginfo('template_url')."/images/no_image.jpg";;	
				}
				$views = get_post_meta($k->ID,'views',true);
				switch($k->post_type){
					case "cgvideo":
						$post_set = "cgvideoset";
						break;
					case "animation":
						$post_set = "animationcat";
						break;
					case "music":
						$post_set = "musicscat";
						break;
					case "games":
						$post_set = "gamescat";
						break;
					case "recreation":
						$post_set = "recreationscat";
						break;
					case "advisory":
						$post_set = "advisorycat";
						break;		
				}
				$arg = array('orderby' => 'term_id', 'order' => 'ASC');
				$terms =  wp_get_object_terms($k->ID, $post_set,$arg); 
				$set = "";
				foreach($terms as $v){
	
						$set .=  $v->name . '&nbsp;&nbsp;';
	
					}

					$html .='<li>
					  <div class="i"><a target="_blank" href="'.get_permalink($k->ID).'"><img src="'.$postimg.'"></a></div>
					  <div class="q"><a target="_blank" class="t" href="'.get_permalink($k->ID).'">'.$k->post_title.'</a>
						<p class="info">收藏数: '.$k->meta_value.' 点击: '.$views.'<br>
						  分类：<a target="_blank" href="">'.$set.'</a></p>
					  </div>
					 </li>';
				}
	}else{
		$current_user = wp_get_current_user();
		$userid = $current_user->ID;
		$table_name = $table_prefix."collect";
		$data = $wpdb->get_results("SELECT * FROM $table_name WHERE  c_userid = ".$userid);	
		foreach ($data as $k){
			
			$postid = $k->c_postid;
			$post_show = get_post($postid);
				
				$postimg = get_post_meta($post_show->ID,'show_image',true);
				if(empty($postimg)){
					$postimg = get_bloginfo('template_url')."/images/no_image.jpg";	
				}
			if($temple==1){
				$html .='<li>
					<a target="_blank" href="'.get_permalink($post_show->ID).'"><img src="'.$postimg.'"></a>
					<a target="_blank" href="'.get_permalink($post_show->ID).'" class="title">'.$post_show->post_title.'</a>
					<div class="c">收藏时间：'.$k->c_time.'</div>
					<div class="q">'.$post_show->post_excerpt.'</div>
				</li>';
			}elseif($temple==2){
				switch($post_show->post_type){
					case "cgvideo":
						$post_set = "cgvideoset";
						break;
					case "animation":
						$post_set = "animationcat";
						break;
					case "music":
						$post_set = "musicscat";
						break;
					case "games":
						$post_set = "gamescat";
						break;
					case "recreation":
						$post_set = "recreationscat";
						break;
					case "advisory":
						$post_set = "advisorycat";
						break;
		
				}
				
				$arg = array('orderby' => 'term_id', 'order' => 'ASC');
				$terms =  wp_get_object_terms($post_show->ID, $post_set,$arg); 
				$set = "";
				foreach($terms as $k){
	
						$set .=  $k->name . '&nbsp;';
	
					}
				$html .='<li>
				  <input type="checkbox" value="'.$post_show->ID.'" name="aids[]" class="check" checked="checked">
				  <div class="i"><a target="_blank" href="'.get_permalink($post_show->ID).'"><img src="'.$postimg.'"></a></div>
				  <div class="q"> <a target="_blank" class="t" href="'.get_permalink($post_show->ID).'"> '.$post_show->post_title.'</a>
					<p class="info">收藏时间：'.$k->c_time.'<br>
					  分类：<a target="_blank">'.$set.'</a></p>
				  </div>
				  <div style="text-align:right" class="admin-a"> <a href="doSubmit.php?act=del&amp;aid='.$post_show->ID.'">[删除]</a> </div>
				</li>';		
			}
		}
	}
	return $html;
}
//显示用户视频
function video(){
	global $table_prefix, $wpdb;
	$current_user = wp_get_current_user();
	$userid = $current_user->ID;
	$data = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS  * FROM ".$table_prefix."posts  WHERE 1=1  AND (".$table_prefix."posts.post_author = ".$userid.") AND (".$table_prefix."posts.post_type != 'specialt') AND  (".$table_prefix."posts.post_status = 'publish' OR ".$table_prefix."posts.post_author = ".$userid." AND ".$table_prefix."posts.post_status = 'pending')  ORDER BY ".$table_prefix."posts.post_date DESC LIMIT 0, 100");
	foreach($data as $v){
		switch($v->post_type){
			case "cgvideo":
				$post_set = "cgvideoset";
				break;
			case "animation":
				$post_set = "animationcat";
				break;
			case "music":
				$post_set = "musicscat";
				break;
			case "games":
				$post_set = "gamescat";
				break;
			case "recreation":
				$post_set = "recreationscat";
				break;
			case "advisory":
				$post_set = "advisorycat";
				break;

		}
		$postcollect = get_post_meta($v->ID,'_postcollect',true);
		$views = get_post_meta($v->ID,'views',true);
		$integration = get_post_meta($v->ID,'_integration',true);
		$postimg = get_post_meta($v->ID,'show_image',true);
		
		$postcollect = $postcollect?$postcollect:0;
		$views = $views?$views:0;
		$integration = $integration?$integration:0;
		$postimg = $postimg?$postimg:get_bloginfo('template_url')."/images/no_image.jpg";
		
		$arg = array('orderby' => 'term_id', 'order' => 'ASC');
		$terms =  wp_get_object_terms($v->ID, $post_set,$arg); 
		$set = "";
		foreach($terms as $k){
			$set .=  $k->name . '&nbsp;';
		}
		if($v->post_status == "pending"){
			$tt = '<span style="color:#F00">*未审核</span>';	
		}
		$html .='<li>
			      <div class="i"><a target="_blank" href="'.get_permalink($v->ID).'"><img src="'.$postimg.'"></a></div>
			      <div class="q"> <a target="_blank" class="t" href="'.get_permalink($v->ID).'"> '.$v->post_title.'</a>
				  '.$tt.'
			      <p class="info"> 发布时间：'.$v->post_date.'<br>
				    分类：'.$set.'<br>
				  点击：'.$views.' 评论：'.$v->comment_count.' 收藏：'.$postcollect.' 评分：'.$integration.' </p>
			    </div>
			    <div style="text-align:right;white-space:nowrap" class="admin-a"> <a href="#video&amp;act=edit&amp;aid='.$v->ID.'">[编辑]</a> <a onclick="return confirm(\'是否确认要删除此稿件?\')" href="#video&amp;act=del&amp;aid='.$v->ID.'">[删除]</a>  </div>
		         </li>';
	
	}
	return $html;

}
//编辑某篇文章
function show_post($id){
		$data = get_post($id);
		$posttags = get_the_tags($id);
		if ($posttags) {
		  foreach($posttags as $tag) {
			$tage .=  $tag->name . ' ';
		  }
		} 
		$postimg = get_post_meta($id,'show_image',true);
		$postimg = $postimg?$postimg:get_bloginfo('template_url')."/images/no_image.jpg";
		$sub_title = get_post_meta($id,'sub_title',true);
		
		switch($data->post_type){
			case "cgvideo":
				$post_set = "cgvideoset";
				break;
			case "animation":
				$post_set = "animationcat";
				break;
			case "music":
				$post_set = "musicscat";
				break;
			case "games":
				$post_set = "gamescat";
				break;
			case "recreation":
				$post_set = "recreationscat";
				break;
			case "advisory":
				$post_set = "advisorycat";
				break;

		}

		$arg = array('orderby' => 'term_id', 'order' => 'ASC');
		$terms =  wp_get_object_terms($id, $post_set,$arg); 
		echo '<div class="body">
					  <style>
						#odi_list table td
						{
							padding: 5px;
							background-color:#FFF;
						}
						#odi_list table tr.head td
						{
							background-color:#EFEFEF;
						}
						#mode_basic_detail
						{
							white-space:nowrap;
						}
						</style>
					  <form onsubmit="return checkSubmit();" enctype="multipart/form-data" method="post" action="doSubmit.php" name="form1" class="mTB10 mL10 mR10">
						<input type="hidden" value="save" name="dopost">
						<div class="up-div">
						  <div class="l"><b>标题</b><span>(必填)</span></div>
						  <div class="r">
							<input type="text" onkeyup="countStrlen(\'title\', \'titleCount\', 40)" style="width:300px;" value="'.$data->post_title.'" maxlength="255" id="title" name="title">
							<span class="color_g"><span id="titleCount">0</span> / 40</span><br>
						  </div>
						</div>
						<div class="up-div">
						  <div class="l"><b>备注名</b><span>(选填)<br>
							可以填写原名称，用户可选择默认显示为此名</span></div>
						  <div class="r">
							<input type="text" onkeyup="countStrlen(\'subtitle\', \'subtitleCount\', 40)" style="width:300px;" value="'.$sub_title.'" maxlength="255" id="subtitle" name="subtitle">
							<span class="color_g"><span id="subtitleCount">0</span> / 40</span><br>
							<span style="color:red">请勿随意填写备注名，如有发现，封号处理</span> </div>
						</div>
						<div class="up-div">
						  <div class="l"><b>标签TAG</b><span>(必填)<br>
							视频关键字，多个请用逗号分开</span></div>
						  <div class="r">
							<input type="text" style="width:300px;" value="'.$tage.'" maxlength="255" id="tags" name="tags" autocomplete="off" class="ui-autocomplete-input" role="textbox" aria-autocomplete="list" aria-haspopup="true">
							<!--<input type="checkbox" checked="checked" value="1" name="keywords_change">
												允许其他人增加--> </div>
						</div>
						<div class="up-div">
						  <div class="l"><b>隶属栏目</b><span>(必填)</span></div>
						  <div class="r">
							<select onclick="chkTips(this.value)" onblur="chkTips(this.value)" size="1" id="typeid" name="typeid">
							  <option disabled="disabled" selected="" value="0">请选择栏目...</option>
							  <optgroup label="CG视频教程">
												  '.select('cgvideoset',$terms[0]-> term_id).'
												  </optgroup>
							  <optgroup label="动画">
												  '.select('animationcat',$terms[0]-> term_id).'
												  </optgroup>
							  <optgroup label="音乐">
												  '.select('musicscat',$terms[0]-> term_id).'
												  </optgroup>
							  <optgroup label="游戏">
												  '.select('gamescat',$terms[0]-> term_id).'
												  </optgroup>
							  <optgroup label="娱乐">
												  '.select('recreationscat',$terms[0]-> term_id).'
												  </optgroup>
							  <optgroup label="资讯">
												  '.select('advisorycat',$terms[0]-> term_id).'
												  </optgroup>
							</select>
							<span id="classtips"></span> </div>
						</div>
						<div class="up-div">
						  
						<div style="display:none" id="div_origav" class="up-div">
						  <div class="l"><b>补档AV号</b><span>(必填)<br>
							仅对UP主自主删除视频有效</span></div>
						  <div class="r">
							<input type="text" style="width:50px;" value="" maxlength="8" name="orig_av" id="orig_av">
						  </div>
						</div>
						<div style="" class="up-div">
						  <div class="l"><b>简介</b><span>(必填)<br>
							视频的内容简介 多页相当于P1简介</span></div>
						  <div class="r">
							<textarea onkeyup="countStrlen(\'description\', \'descCount\', 200)" style="height:65px;width:380px" id="description" name="description">'.$data->post_excerpt.'</textarea>
							<span class="color_g"><span id="descCount">0</span> / 200</span><br>
						  </div>
						</div>

						<div class="up-div">
						  <div class="l"><b>封面缩略图</b> <span>(分辨率120X90 JPEG或PNG)<br>
							如沒有上传将不显示视频图片</span></div>
						  <div class="r">
							<input type="file" style="width:408px" id="litpic" name="litpic" class="file">
							<br><img width="120" height="90" src="'.$postimg.'">
						  </div>
						</div>
						<div class="up-div">
						  <div style="padding:3px; font-size:14px" id="editor_mode_select"> 编辑器模式:
							<input type="radio" onclick="select_Editor_Mode(this.value)" value="0" id="editor_mode_single" name="editor_mode">
							<label for="editor_mode_single">普通模式</label>
							<input type="radio" value="1" id="editor_mode_advance" checked="checked" onclick="select_Editor_Mode(this.value)" name="editor_mode">
							<label style="color:red" for="editor_mode_advance">代码模式</label>
							<br>
						  </div>
						</div>
						<div id="odi_list" style="display: none;">
						  <table cellspacing="1" cellpadding="1" bgcolor="#999999">
							<tbody>
							  <tr class="head">
								<td nowrap="">来源</td>
								<td width="350">视频ID</td>
								<td nowrap="">操作</td>
							  </tr>
							  <tr>
								<td><select id="odi_source">
									<option value="sina">新浪</option>
									<option value="youku">优酷</option>
									<option value="qq">腾讯</option>
									<!--<option value="6cn">6间房</option>-->
								  </select></td>
								<td id="odi_link_container"><input type="text" value="" size="60" style="width:340px" id="odi_link"></td>
								<td><input type="button" onclick="addNew()" id="btn_basic_add" value=" 添加 "></td>
							  </tr>
							</tbody>
						  </table>
						</div>
						<input id="auto_action" type="hidden" value="edit_post" name="auto_action">
						<input  type="hidden" value="'.$data->post_type.'" name="post_type">
						<input  type="hidden" value="'.$id.'" name="post_id">
						<div class="up-div">
						  <div style="display: block;" id="mode_advance">
							<p style="color:red">↓↓↓↓↓↓投稿代码请放到下面↓↓↓↓↓↓</p>
							<textarea name="body" style="border:2px thin #CCC; width:500px; height:280px" id="body">'.$data->post_content.'</textarea>
							<br>
							<!--<input type="button" value="可点此使用转换器转换" style="font-size:14px;padding:5px" onclick="window.open(\'http://my-acg.com/bilibili.htm\')">--> 
							<span style="font-size:16px; color:blue"><!--或-->
							<input type="button" value="点这里查看投稿范例" style="font-size:14px;padding:5px" onclick="if ($(\'#manual_post_help:visible\').length){ $(\'#manual_post_help\').hide(\'fold\'); }else{ $(\'#manual_post_help\').show(\'fold\');}">
							</span>
							<div style="display:none" id="manual_post_help">
							  <pre>
										
										新浪地址如 http://video.sina.com.cn/v/b/<font color="red">33372250</font>-1747442072.html
										则发布代码应为
										[mukio]vid=33372250[/mukio]
										
										QQ地址如 http://cgi.video.qq.com/v1/videopl?v=<font color="red">69Y7qUEoJaI</font>
										则发布代码应为
										[mukio]vid=69Y7qUEoJaI&type=qq[/mukio]
										
										优酷代码
										[mukio]vid=eerwer&type=youku[/mukio]
										
										flv等视频文件
										[mukio ]file=http://6.cn/p/WYN2dzJ07Mah92zCwYB9Tg.swf[/mukio]
										
										</pre>
							</div>
						  </div>
						</div>
						<hr>
						<br>
						<div class="up-div"> <font size="5" color="#990000" style="line-height:200%">★任何一名优秀的UP主，都应该拒绝投稿渣画质视频！★</font><br>
						  <font size="5" color="#990000" style="line-height:200%">★网站拒绝任何明文标注版权物和低俗稿件!★</font><br>
						  <h2>投稿说明</h2>
						  <font size="2" color="red">为了避免投稿视频撞车（即，视频重复）投稿前请仔细搜索有无您想投稿的视频。<br>
						  如果您的投稿视频被退回,那么说明您投稿中的相关内容不完整或投稿代码模式没有按照范例的标准进行填写。 </font> </div>
						<div class="up-div">
						  <button type="submit" class="button2">提交</button>
						  <button onclick="location.reload();" type="reset" class="button2 mL10">重置</button>
						</div>
					  </form>
					  <script language="JavaScript" src="js/member_new.js"></script> 
					</div>';
}

function most_viewed($mode = '', $limit = 10,$classname = 'hit_list',$days = '-7',$showpost = false,$sql = '',$display = true) {
    global $wpdb, $post;
    $where = '';
    $temp = '';
    $output = '';
    if(!empty($mode) && $mode != 'both') {
        $where = "post_type = '$mode'";
    } else if(empty($mode) && $showpost == true) {
        $where = $sql;
    }else{
		$where = '1=1';
	}
    $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date >= '".date('Y-m-d', strtotime($days.' days'))."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER  BY views DESC LIMIT $limit");
    if($most_viewed) {
        foreach ($most_viewed as $key => $post) {
			$subtitle = get_post_meta($post->ID,'sub_title',true);
			if(!empty($subtitle)){
				$subt = $subtitle;
			}else{
				$subt = get_the_title();
			}
			$thumb = get_post_meta($post->ID,'show_image',true);
			if(!empty($thumb)){
				$thumb = '<img src="'.$thumb.'">';
			}else{
				$thumb = '<img src="'.get_bloginfo('template_url').'/images/no_image.jpg">';	
			}
			$start_time = get_post_meta($post->ID,'start_time',true);
			if(!empty($start_time)){
				$start_time = $start_time;
			}else{
				$start_time = '00:00';
			}
			$collect = get_post_meta($post->ID, '_postcollect', true);
			if(empty($collect)){ $collect = 0;}else{ $collect = $collect; }
			$integration = get_post_meta($post->ID, '_integration', true);
			if(empty($integration)){ $integration = 0;}else{ $integration = $integration; }
			$views = get_post_meta($post->ID, 'views', true);
			if(empty($views)){ $views = 0;}else{ $views = $views; }
			$user_info = get_userdata($post->post_author);			
            $post_title = get_the_title();
			$keys = $key+1;
			$str = mb_strimwidth(strip_tags(apply_filters('the_title',$post_title)), 0, 26,"...",'UTF-8');			
			$output .= '<div id="jq_po" class="po" gk="'.$views.'" sc="'.$collect.'" pl="'.$post->comment_count .'" dm="'.$v->comment_count .'" subtitle="'.$subt.'" lm="" tg="'.substr($post->post_date,0,-3).'" up="'.$user_info->display_name .'" txt="'.$post->post_title .'" pf="'.$integration.'" yb="4">
                <a href="'.get_permalink($post->ID) .'" target="_blank">'.$thumb.'
                <div class="vbg"></div>
                <div class="t">'.$post->post_title .'</div></a>
                <div class="z">
                <b>'.$start_time.'</b>
                <i>'.$integration.'</i>
                </div>
                <div class="i"><b class="c1">'.$views.'</b><b class="c2">'.$post->comment_count.'</b></div>
            </div>';
        }
    } else {
        $output = '<li style="text-align:center; padding:10px 0;">暂无推荐</li>'."\n";
    }
    if($display) {
        echo $output;
    } else {
        return $output;
    }
}

function hot_viewed($mode = '', $limit = 10,$classname = 'hit_list',$days = '-7',$showpost = false,$sql = '',$display = true) {
    global $wpdb, $post;
    $where = '';
    $temp = '';
    $output = '';
    if(!empty($mode) && $mode != 'both') {
        $where = "post_type = '$mode'";
    } else if(empty($mode) && $showpost == true) {
        $where = $sql;
    }else{
		$where = '1=1';
	}
    $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date >= '".date('Y-m-d', strtotime($days.' days'))."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER  BY views DESC LIMIT $limit");
    if($most_viewed) {
        foreach ($most_viewed as $key => $post) {
			$thumb = get_post_meta($post->ID,'show_image',true);
			if(!empty($thumb)){
				$thumb = '<img src="'.$thumb.'">';
			}else{
				$thumb = '<img src="'.get_bloginfo('template_url').'/images/no_image.jpg">';	
			}
			$views = get_post_meta($post->ID, 'views', true);
			if(empty($views)){ $views = 0;}
			$user_info = get_userdata($post->post_author);			
            $post_title = get_the_title();
			$str = mb_strimwidth(strip_tags(apply_filters('the_title',$post_title)), 0, 26,"...",'UTF-8');			
			$output .= '<li><a href="'.get_permalink($post->ID).'" target="_blank">'.$thumb.'<div class="title">'.$str.'</div></a><div class="i"><b class="c1">'.$views.'</b><b class="c2">'.$post->comment_count.'</b></div></li>';
        }
    } else {
        $output = '<li style="text-align:center; padding:10px 0;">暂无热门视频</li>'."\n";
    }
    if($display) {
        echo $output;
    } else {
        return $output;
    }
}

function high_score($mode = '',$limit = 10,$display = true) {
    global $wpdb, $post;
    $where = '';
    $temp = '';
    $output = '';
    if(!empty($mode) && $mode != 'both') {
        $where = "post_type = '$mode'";
    }else{
		$where = '1=1';
	}
    $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS integration FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE $where AND post_status = 'publish' AND meta_key = '_integration' AND post_password = '' ORDER  BY integration DESC LIMIT $limit");
    if($most_viewed) {
        foreach ($most_viewed as $key => $post) {
			$thumb = get_post_meta($post->ID,'show_image',true);
			if(!empty($thumb)){
				$thumb = '<img src="'.$thumb.'">';
			}else{
				$thumb = '<img src="'.get_bloginfo('template_url').'/images/no_image.jpg">';	
			}
			$views = get_post_meta($post->ID, 'views', true);
			if(empty($views)){ $views = 0;}
			$user_info = get_userdata($post->post_author);			
            $post_title = get_the_title();
			$str = mb_strimwidth(strip_tags(apply_filters('the_title',$post_title)), 0, 26,"...",'UTF-8');			
			$output .= '<li><a href="'.get_permalink($post->ID).'" target="_blank">'.$thumb.'<div class="t">'.$str.'</div></a><div class="i"><b class="c1">'.$views.'</b><b class="c2">'.$post->comment_count.'</b></div></li>';
        }
    } else {
        $output = '<li style="text-align:center; padding:10px 0;">暂无高分视频</li>'."\n";
    }
    if($display) {
        echo $output;
    } else {
        return $output;
    }
}

function new_post_list($mode = '',$limit = 10,$display = true) {
    global $wpdb, $post;
    $where = '';
    $temp = '';
    $output = '';
    if(!empty($mode) && $mode != 'both') {
        $where = "post_type = '$mode'";
    }else{
		$where = '1=1';
	}
    $most_viewed = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE $where AND post_status = 'publish' AND post_password = '' ORDER BY post_date DESC LIMIT $limit");
    if($most_viewed) {
        foreach ($most_viewed as $key => $post) {
			$thumb = get_post_meta($post->ID,'show_image',true);
			if(!empty($thumb)){
				$thumb = '<img src="'.$thumb.'">';
			}else{
				$thumb = '<img src="'.get_bloginfo('template_url').'/images/no_image.jpg">';	
			}
			$views = get_post_meta($post->ID, 'views', true);
			if(empty($views)){ $views = 0;}
			$user_info = get_userdata($post->post_author);			
            $post_title = get_the_title();
			$str = mb_strimwidth(strip_tags(apply_filters('the_title',$post_title)), 0, 26,"...",'UTF-8');			
			$output .= '<li><a href="'.get_permalink($post->ID).'" target="_blank">'.$thumb.'<div class="t">'.$str.'</div></a><div class="i"><b class="c1">'.$views.'</b><b class="c2">'.$post->comment_count.'</b></div></li>';
        }
    } else {
        $output = '<li style="text-align:center; padding:10px 0;">暂无投稿视频</li>'."\n";
    }
    if($display) {
        echo $output;
    } else {
        return $output;
    }
}

function page_list_view($post_type = 'All',$taxonomy_type = '',$show_num = '10'){

$categories = get_categories(array('taxonomy'=>$taxonomy_type,'hide_empty'=>'1')); 
foreach($categories as $key=>$val){
	$cslug = $val->slug;  $cname = $val->name; $cid = $val->cat_ID;
	$args = array(
	   'numberposts' => $show_num,
	   'post_type' => $post_type,
	   $taxonomy_type => $cslug,
	   'post_status' => 'publish'
	);
	$show_posts = get_posts ($args);

?>
<div class="z-l f-list">
    	<div class="hd"><div class="hdt"><a href="<?php echo get_permalink($v->ID); ?>"><?php echo $cname; ?></a><span class="sub_addnew" id="subadd_24"></span></div><div class="more"><a href="<?php echo get_bloginfo('url'); ?>/<?php echo $taxonomy_type; ?>/<?php echo $cslug; ?>" target="_blank">查看更多</a></div></div>
    	<div class="vidbox">
        	<?php 
				foreach($show_posts as $k=>$v){ 
				$subtitle = get_post_meta($v->ID,'sub_title',true);
				if(!empty($subtitle)){
					$subt = $subtitle;
				}else{
					$subt = get_the_title();
				}
				$thumb = get_post_meta($v->ID,'show_image',true);
				if(!empty($thumb)){
					$thumb = '<img src="'.$thumb.'">';
				}else{
					$thumb = '<img src="'.get_bloginfo('template_url').'/images/no_image.jpg">';	
				}
				$start_time = get_post_meta($v->ID,'start_time',true);
				if(!empty($start_time)){
					$start_time = $start_time;
				}else{
					$start_time = '00:00';
				}
				$collect = get_post_meta($v->ID, '_postcollect', true);
				if(empty($collect)){ $collect = 0;}else{ $collect = $collect; }
				$integration = get_post_meta($v->ID, '_integration', true);
				if(empty($integration)){ $integration = 0;}else{ $integration = $integration; }
				$views = get_post_meta($v->ID, 'views', true);
				if(empty($views)){ $views = 0;}else{ $views = $views; }
				$user_info = get_userdata($v->post_author);
			?>
            <div id="jq_po_5" class="po" gk="<?php echo $views; ?>" sc="<?php echo $collect; ?>" pl="<?php echo $v->comment_count; ?>" dm="<?php echo $v->comment_count; ?>" subtitle="<?php echo $subt; ?>" lm="" tg="<?php echo substr($v->post_date,0,-3); ?>" up=" <?php echo $user_info->display_name; ?>" txt="<?php echo $v->post_title; ?>" pf="<?php echo $integration; ?>" yb="4">
                <a href="<?php echo get_permalink($v->ID); ?>" target="_blank"><?php echo $thumb; ?>
                <div class="vbg"></div>
                <div class="t"><?php echo $v->post_title; ?></div></a>
                <div class="z">
                <b><?php echo $start_time; ?></b>
                <i><?php echo $integration; ?></i>
                </div>
                <div class="i"><b class="c1"><?php echo $views; ?></b><b class="c2"><?php echo $v->comment_count; ?></b></div>
            </div>               
			<?php } ?>
        </div>
    </div>
	
<?php	} 
}

//专题分类列表
function terms_list(){
	//$args = array( 'taxonomy' => 'specialtcat' );
	global $wpdb;
	$cats = $wpdb->get_results("SELECT {$wpdb->prefix}terms.term_id, name
                            FROM {$wpdb->prefix}term_taxonomy, {$wpdb->prefix}terms
                            WHERE {$wpdb->prefix}term_taxonomy.term_id = {$wpdb->prefix}terms.term_id
                            AND taxonomy = 'specialtcat'");
	foreach($cats as $k){
		$html .= '<a styleid="'.$k->term_id.'" href="javascript:;">'.$k->name.'</a>';	
	}
	return $html;
}

//后台logo
add_filter('login_headerurl', create_function(false,"return get_bloginfo( 'siteurl' );"));
add_filter('login_headertitle', create_function(false,"return get_bloginfo( 'description’' );"));
function nowspark_login_head() {
    echo '<style type="text/css">h1 a { background: url('.get_bloginfo('template_directory').'/images/header/logo.jpg) 50% 50% no-repeat !important; }</style>';
}
add_action("login_head", "nowspark_login_head");//modify the background image

//显示专题列表
function specialt_list(){
	global $table_prefix, $wpdb;
	$current_user = wp_get_current_user();
	$userid = $current_user->ID;
	$data = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS  * FROM ".$table_prefix."posts  WHERE 1=1  AND (".$table_prefix."posts.post_author = ".$userid.") AND (".$table_prefix."posts.post_type = 'specialt') AND  (".$table_prefix."posts.post_status = 'publish' OR  ".$table_prefix."posts.post_status = 'pending')  ORDER BY ".$table_prefix."posts.post_date DESC LIMIT 0, 100");
	
	foreach ($data as $val){
		if($val->post_status == "pending"){
			$tt = '<span style="color:#F00">*未审核</span>';	
		}
		$postcollect = get_post_meta($val->ID,'_postcollect',true);
		$views = get_post_meta($val->ID,'views',true);
		$postcollect = $postcollect?$postcollect:0;
		$views = $views?$views:0;
				
		$html .='<li><div class="i"><a target="_blank" href="'.get_permalink($val->ID).'">'.get_the_post_thumbnail($val->ID, array(128,128) ).'</a></div><div class="q"> <a target="_blank" class="t" href="'.get_permalink($val->ID).'">'.$val->post_title.'</a>'.$tt.'<p class="info"> 发布时间：'.$val->post_date.'<br>点击：'.$views.' 收藏：'.$postcollect.' </p></div><div style="text-align:right;white-space:nowrap" class="admin-a"> <a href="#sp&amp;act=edit&amp;spid='.$val->ID.'">[编辑]</a> </div></li>'; 
	}
	return $html;		
}
//编辑专题
function editSpecialt($post_id){
	$data = get_post($post_id);
	$sp_alias = get_post_meta($post_id, 'sp_alias', true);
	$img = get_the_post_thumbnail( $data->ID, array(128, 128), array('alt'=>$data->post_title) )?get_the_post_thumbnail( $data->ID, array(128, 128), array('alt'=>$data->post_title,'id'=> "imghead") ):'<img border="0" id="imghead" src="http://static.hdslb.com/images/transparent.gif">';
	
	$html  = '<div class="nav"><a href="#sp">我的专题</a><a href="#sp&amp;act=new">创建专题</a></div>
			 <script language="JavaScript" src="js/common.js"></script>
				<div class="body">
				  <form enctype="multipart/form-data" method="post" action="doSubmit.php" name="form1">
					<div class="sp_post">
					  <div id="preview"> '.$img.' </div>
					  <ul>
						<li><span>专题标题:<br>
						  <i class="i">(必填)</i></span>
						  <div class="left">
							<input type="text" readonly="readonly" value="'.$data->post_title.'" style="width:300px;" name="title" id="sp_title">
							
							<div class="info"></div>
						  </div>
						</li>
						<li><span>添加同义词<br>
						  <i>(选填)</i></span>
						  <div class="left">
							<input type="text" style="width:300px;" name="sp_alias" id="sp_alias" value="'.$sp_alias.'">
							<i>用半角逗号(,)分隔</i><i id="sp_alias_msg"></i>
							<div style="color:red" class="info">请勿随意填写同义词,凡带有不标准含义或者无意义同义词均不予通过,我们将严格审查,恶意填写将被封停处理!</div>
						  </div>
						</li>
						<li> <span>缩略图:</span>
						  <div class="left">
							<input type="file" onchange="previewImage(this)" style="width:300px;" name="img" id="imgup">
							<i>(分辨率128x128)</i></div>
						</li>
						<li><span>修改理由:<br>
						  <i>1000字以内</i></span>
						  <div class="left">
							<textarea name="edit_reason" id="edit_reason"></textarea>
						  </div>
						</li>
						<li id="bangumi_date_layer"> <span>番剧播出时间:</span>
						  <div class="left">
							<input type="text" value="'.date('Y-m-d',strtotime($data->post_date)).'" name="bangumi_date" id="bangumi_date">
						  </div>
						</li>
						<li><span>专题介绍:<br>
						  <i>1000字以内</i></span>
						  <div class="left">
							<textarea name="description" id="description"> '.$data->post_excerpt.'</textarea>
						  </div>
						</li>
					  </ul>
					  <input type="hidden" value="" id="id_styleid" name="styleid">
					  <div class="cnt">
						<input type="hidden" value="'.$post_id.'" name="spid">
						<input type="hidden" value="edit_specialt" name="auto_action">
						<input type="submit" value="提交" class="dbutton">
					  </div>
					</div>
				  </form>
				</div>';
			return $html;
	}